package com.sky.proxy.cglibProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * <p> 定义一个被代理类
 * <p> 定义一个拦截器并实现接口 MethodInterceptor
 * <p> 代理工厂类  使用 拦截器 和 被代理类 生成 代理对象
 * <p> 通过代理对象调用方法
 *
 * @author : wushikai
 * <p>
 * date : 2022-03-09
 */
public class ServiceInterceptor implements MethodInterceptor {

    /**
     * All generated proxied methods call this method instead of the original method.
     * The original method may either be invoked by normal reflection using the Method object,
     * or by using the MethodProxy (faster).
     * @param arg0 "this", the enhanced object
     * @param method intercepted Method
     * @param args argument array; primitive types are wrapped
     * @param proxy used to invoke super (non-intercepted method); may be called as many times as needed
     * @throws Throwable any exception may be thrown; if so, super method will not be invoked
     * @return any value compatible with the signature of the proxied method. Method returning void will ignore this value.
     * @see MethodProxy
     */
    @Override
    public Object intercept(Object arg0, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println( "增强对象类型  arg0.getClass(): " + arg0.getClass().getCanonicalName());
        System.out.println("被拦截方法: " + method.getName());
        System.out.println( "真实的代理方法: "+proxy.getSignature());
        for (Object arg : args) {
            System.out.println("被代理方法参数类型: " + arg.getClass());
            System.out.println("被代理方法参数值: " + arg);
        }

        Object result = proxy.invokeSuper(arg0, args);

        System.out.println( "被代理方法返回值: " +   result);
        System.out.println("真实的代理对象: " + proxy.toString());
        System.out.println("/*-----------------      -------------*/");
        return result;
    }
}


